import { summaryTotalData, summaryHistogram, getData } from '../services/summary-controller';

export default {
  namespace: 'SummaryModel',

  state: {
    queryParam: {
      histogramPrefix: 'txh',
      groupBy: 'day',
      min: undefined,
      max: undefined,
    },
    data: {
      // 汇总数据
      totalData: undefined,
      // 直方图数据
      histogram: undefined,
      // 表格数据
      tableData: undefined,
    },
  },

  effects: {
    // 查询页面所有数据
    *query({ payload }, { select, call, put }) {
      const { currentSysName } = yield select(state => state.GlobalEnumModel);
      let { queryParam } = yield select(state => state.SummaryModel);
      queryParam = { ...queryParam, index: currentSysName, ...payload };
      const { histogramPrefix, groupBy, max, min, index } = queryParam;
      // 请求数据
      const totalData = yield call(summaryTotalData, { groupBy, max, min, index });
      if (!totalData) return;
      const histogram = yield call(summaryHistogram, { histogramPrefix, max, min, index });
      if (!histogram) return;
      const tableData = yield call(getData, { groupBy, max, min, index });
      if (!tableData) return;
      // 保存数据
      yield put({ type: 'save', payload: { queryParam, data: { totalData, histogram, tableData } } });
      yield put({ type: 'GlobalEnumModel/save', payload: { currentSysName: index } });
    },
    // 查询直方图数据
    *queryHistogram({ payload }, { select, call, put }) {
      const { currentSysName } = yield select(state => state.GlobalEnumModel);
      let { queryParam, data } = yield select(state => state.SummaryModel);
      queryParam = { ...queryParam, index: currentSysName, ...payload };
      const { histogramPrefix, max, min, index } = queryParam;
      const histogram = yield call(summaryHistogram, { histogramPrefix, max, min, index });
      if (!histogram) return;
      data = { ...data, histogram };
      // 保存数据
      yield put({ type: 'save', payload: { queryParam, data } });
      yield put({ type: 'GlobalEnumModel/save', payload: { currentSysName: index } });
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
